#include <lib/eb_array.h>
#include <lib/eb_string.h>
#include <mm/mem.h>
#include <kernel/syslog.h>


static bool eb_dupli_string(char **ret_str, char *str)
{
    *ret_str = kmalloc(eb_strlen(str) + 1);
    if(*ret_str == NULL) {
        return false;
    }

    eb_strcpy(*ret_str, str);

    return true;
}


int eb_str_array_append(eb_array_t *array, char *str)
{
    eb_array_str_t *node = kmalloc(sizeof(eb_array_str_t));
    if(node == NULL) {
        return -1;
    }

    node->string = NULL;

    int ret = eb_dupli_string(&node->string, str);
    if(ret) {
        kfree(node);
        return 0;
    }

    list_add_node_at_tail(&array->head, &node->node);
    array->count ++;

    return 0;
}


int eb_int_array_append(eb_array_t *array, int value)
{
    eb_array_int_t *node = kmalloc(sizeof(eb_array_int_t));
    if(node == NULL) {
        return -1;
    }

    node->value = value;
    list_add_node_at_tail(&array->head, &node->node);
    array->count ++;

    return 0;
}


int eb_ptr_array_append(eb_array_t *array, void* ptr)
{
    eb_array_ptr_t *node = kmalloc(sizeof(eb_array_ptr_t));
    if(node == NULL) {
        return -1;
    }

    node->p = ptr;
    list_add_node_at_tail(&array->head, &node->node);
    array->count ++;

    return 0;
}


int eb_str_array_delete(eb_array_t *array)
{
    if(array->count == 0) {
        return 0;
    }

    list_node_t *node = list_next_node(&array->head);

    for(int i = 0; i < array->count; i++) {
        
        eb_array_str_t *array_node = container_of(node, eb_array_str_t, node);
        kfree(array_node->string);
        kfree(array_node);

        node = list_next_node(node);
    }
    return 0;
}


int eb_int_array_delete(eb_array_t *array)
{
    if(array->count == 0) {
        return 0;
    }

    list_node_t *node = list_next_node(&array->head);

    for(int i = 0; i < array->count; i++) {
        
        eb_array_int_t *array_node = container_of(node, eb_array_int_t, node);
        kfree(array_node);

        node = list_next_node(node);
    }
    return 0;
}


int eb_ptr_array_delete(eb_array_t *array)
{
    if(array->count == 0) {
        return 0;
    }

    list_node_t *node = list_next_node(&array->head);

    for(int i = 0; i < array->count; i++) {
        
        eb_array_ptr_t *array_node = container_of(node, eb_array_ptr_t, node);
        if(array_node->p) {
            kfree(array_node->p);
        }
        kfree(array_node);

        node = list_next_node(node);
    }
    return 0;
}
